package net.hvacapp.cmvrfforandroid.ui.project;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;

import com.mirror.android.common.util.ScreenUtils;
import com.mirror.android.common.util.StringUtils;

import net.hvacapp.cmvrfforandroid.R;
import net.hvacapp.cmvrfforandroid.adapter.BaseAdapterHelper;
import net.hvacapp.cmvrfforandroid.adapter.QuickAdapter;
import net.hvacapp.cmvrfforandroid.http.BasicHttpClient;
import net.hvacapp.cmvrfforandroid.http.HttpCallbackHandle;
import net.hvacapp.cmvrfforandroid.http.HttpConstant;
import net.hvacapp.cmvrfforandroid.manager.AccountManager;
import net.hvacapp.cmvrfforandroid.manager.ProjectManager;
import net.hvacapp.cmvrfforandroid.ui.BaseActivity;
import net.hvacapp.cmvrfforandroid.ui.MainTabBarActivity;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetIndoorEquipDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GetRoomDataResp;
import net.hvacapp.cmvrfforandroid.ui.project.model.GuidData;
import net.hvacapp.cmvrfforandroid.ui.project.model.ProjectInfoData;
import net.hvacapp.cmvrfforandroid.ui.project.model.RoomData;
import net.hvacapp.cmvrfforandroid.utils.AnnotationUtil;
import net.hvacapp.cmvrfforandroid.utils.NumberUtil;
import net.hvacapp.cmvrfforandroid.widget.IOSAlertView;
import net.hvacapp.cmvrfforandroid.widget.ProjectActionView;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenu;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuCreator;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuItem;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuLayout;
import net.hvacapp.cmvrfforandroid.widget.swipemenulistview.SwipeMenuListView;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@EActivity(R.layout.activity_project_step4)
public class ProjectStep4Activity extends BaseActivity {

    private final int Add_New_Room = 1;
    private final int Edit_Room = 2;

    private final int Select_SNJ_XS = 3;
    private final int Select_QXSYKT_XS = 4;


    @ViewById(R.id.action_view)
    ProjectActionView mActionView;

    @ViewById(R.id.tv_snj)
    TextView mAutoSelSnjTv;
    @ViewById(R.id.tv_qxsykt)
    TextView mAutoSelQxsyktTv;


    private Dialog mProgressDlg;

    @ViewById(R.id.lv_templete)
    SwipeMenuListView mTempleteLv;

    private QuickAdapter<RoomData> mQuickAdapter;
    private ArrayList<RoomData> mRoomDatas;
    private RoomData mEditRoom;



    /**
     * 页面加载完后执行
     */
    @AfterViews
    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        initViews();
        initEvent();
    }

    /***
     * 初始化视图
     */
    private void initViews() {
        mActionView.setActionInfo(ProjectManager.getInstance().getTotal(), ProjectManager.getInstance().getCurrent());

        if (ProjectManager.getInstance().isSwjEnable()) {
            mAutoSelSnjTv.setVisibility(View.VISIBLE);
        }
        if (ProjectManager.getInstance().isQxsyktEnable()) {
            mAutoSelQxsyktTv.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 初始化
     */
    @Override
    public void initBoot() {
        setupToolbar(R.string.title_for_project, "房间配置", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(AnnotationUtil.get(MainTabBarActivity.class));
            }
        });

//        int ids[] = {R.id.action_new_room};
//        int icons[] = {R.drawable.new_project};
//        setupToolbarMenuItem(ids, icons, new String[]{"新建房间"}, null);
        setButton1Info("新建房间", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProjectStep4Activity.this, AnnotationUtil.get(ProjectNewRoomActivity.class));
                startActivityForResult(intent, Add_New_Room);
            }
        });


        if (mQuickAdapter == null){
            mQuickAdapter = new QuickAdapter<RoomData>(context, R.layout.two_lines_cell_item) {
                @Override
                protected void convert(BaseAdapterHelper helper, RoomData item) {

                    helper.setImageResource(R.id.iv_selected_mark, R.drawable.user_selection_hint);
                    helper.setVisible(R.id.iv_selected_mark, true);
                    helper.setText(R.id.tv_title, item.getName());
                    helper.setText(R.id.tv_description, NumberUtil.formateDouble(item.getArea()) + "平米 " + NumberUtil.formateDouble(item.getLoad()) + "W");
                }
            };
        }

        mTempleteLv.setAdapter(mQuickAdapter);

        // 设置左侧滑menu
        SwipeMenuCreator menuCreator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                SwipeMenuItem menuItem = new SwipeMenuItem(ProjectStep4Activity.this);
                menuItem.setBackground(new ColorDrawable(Color.parseColor("#FFBA7F")));
                menuItem.setWidth((int) ScreenUtils.dpToPx(ProjectStep4Activity.this, 80));
                menuItem.setTitleColor(getResources().getColor(R.color.cm_navigation_red_color));
                menuItem.setTitleSize(14);
                menu.addMenuItem(menuItem);
                menuItem.setTitle("删除");

//                if (menu.getViewType() == ArticleAdapter.ARTICLE_NOT_READ) {
//                    menuItem.setIcon(R.drawable.information_center_mark_article_read_icon);
//                    menuItem.setTitle("标为已读");
//
//                } else if (menu.getViewType() == ArticleAdapter.ARTICLE_READ) {
//                    menuItem.setIcon(R.drawable.information_center_mark_article_not_read_icon);
//                    menuItem.setTitle("标为未读");
//                }
            }
        };
        mTempleteLv.setMenuCreator(menuCreator);
    }


    /**
     * 初始化数据
     */
    @Override
    public void initData(Intent intent) {
        mRoomDatas = new ArrayList<>();
        loadProjectRooms();
    }



    /**
     * 页面名称
     */
    @Override
    public String getName() {
        return "";
    }

    /**
     * toolbar上的按钮点击事件
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_new_room:

                Intent intent = new Intent(this, AnnotationUtil.get(ProjectNewRoomActivity.class));
                startActivityForResult(intent, Add_New_Room);
                break;
            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    private void initEvent() {
        mActionView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //上一步
                ProjectManager.getInstance().goLastStep();
                finish();
            }
        });

        mActionView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步
                goNextStep();
            }
        });

        mTempleteLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mEditRoom = (RoomData) parent.getItemAtPosition(position);

                Intent intent = new Intent(ProjectStep4Activity.this, AnnotationUtil.get(RoomInfoActivity.class));
                Bundle bundle = new Bundle();
                bundle.putParcelableArrayList("rooms", mRoomDatas);
                bundle.putInt("index", position);
                intent.putExtras(bundle);
                startActivityForResult(intent, Edit_Room);
            }
        });

        mTempleteLv.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {

            @Override
            public boolean onMenuItemClick(SwipeMenuLayout swipeMenuLayout, int position, SwipeMenu menu, int index) {
                RoomData room = mQuickAdapter.getItem(position);
                deleteOneRoom(room);
                return true;
            }
        });

        mAutoSelSnjTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProjectStep4Activity.this, AnnotationUtil.get(SelectXsActivity.class));
                Bundle bundle = new Bundle();
                bundle.putBoolean("multiple", false);
                bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_SNJ);
                intent.putExtras(bundle);
                startActivityForResult(intent, Select_SNJ_XS);
            }
        });

        mAutoSelQxsyktTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(ProjectStep4Activity.this, AnnotationUtil.get(SelectXsActivity.class));
                Bundle bundle = new Bundle();
                bundle.putBoolean("multiple", false);
                bundle.putString("tag", ProjectInfoData.MACHINE_TAG_FOR_QXSYKT);
                intent.putExtras(bundle);
                startActivityForResult(intent, Select_QXSYKT_XS);
            }
        });


    }

    private void goNextStep() {
        ProjectManager.getInstance().goNextStep();
        if (ProjectManager.getInstance().swjPageEnabled()) {
            //跳转到室外机页面
            startActivity(AnnotationUtil.get(ProjectStep5Activity.class));
        }
        else if (ProjectManager.getInstance().qrjhqPageEnabled()) {
            //跳转到全热交换器页面
            startActivity(AnnotationUtil.get(ProjectStep6Activity.class));
        }
        else if (ProjectManager.getInstance().kqnrsjPageEnabled()) {
            //跳转到空气能热水机页面
            startActivity(AnnotationUtil.get(ProjectStep7Activity.class));
        }
        else {
            //跳转到设备报价页面
            startActivity(AnnotationUtil.get(ProjectStep8Activity.class));
        }
    }


    private void loadProjectRooms() {
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());

        mProgressDlg = createProgressBarDialog(this, "数据加载中...");
        mProgressDlg.show();

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_ALL_ROOMS, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetRoomDataResp>() {
            @Override
            public void onSuccess(GetRoomDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mRoomDatas.clear();
                mQuickAdapter.clear();
                mRoomDatas.addAll(obj.getGetRoomsResult());
                mQuickAdapter.addAll(obj.getGetRoomsResult());
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("获取房间列表失败，请重试！");
            }
        });
    }

    private void addNewRoom(final RoomData newRoom) {
        Map<String, Object> param = new HashMap<>();
        param.put("roomData", newRoom);

        String url = HttpConstant.HTTP_PUT_PROJECT_ROOM
                + "?pid=" + ProjectManager.getInstance().getProjectData().getGuidId()
                + "&tk=" + AccountManager.getInstance().getToken();

        mProgressDlg = createProgressBarDialog(this, "添加新房间中...");
        mProgressDlg.show();

        BasicHttpClient.httpPutAsync(url, param, new HttpCallbackHandle<GetRoomDataResp>() {
            @Override
            public void onSuccess(GetRoomDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                newRoom.setGuidId(obj.getCreateRoomResult());
                mRoomDatas.add(newRoom);
                mQuickAdapter.add(newRoom);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("添加房间失败，请重试！");
            }
        });
    }

    private void deleteOneRoom(final RoomData room) {

        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("rid", room.getGuidId());

        mProgressDlg = createProgressBarDialog(this, "删除房间中...");
        mProgressDlg.show();

        BasicHttpClient.httpDeleteAsync(HttpConstant.HTTP_DELETE_PROJECT_ROOM, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetRoomDataResp>() {
            @Override
            public void onSuccess(GetRoomDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                mRoomDatas.remove(room);
                mQuickAdapter.remove(room);
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                showMessage("删除房间失败，请重试！");
            }
        });
    }



    /**
     * 回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != this.RESULT_OK) {
            return;
        }
        if (requestCode == Add_New_Room) {
            if (data != null) {
                RoomData newRoom = data.getParcelableExtra("room");
                addNewRoom(newRoom);
            }
        }
        else if (requestCode == Edit_Room) {
            loadProjectRooms();
        }
        else if (requestCode == Select_SNJ_XS) {
            if (data != null) {
                List<GuidData> xs = data.getParcelableArrayListExtra("device");
                if (xs != null && xs.size() > 0) {
                    //开始自动选型
                    ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SNJ, xs.get(0).getGuidId());
                    getDefaultSNJDevice();
                }
            }
        } else if (requestCode == Select_QXSYKT_XS) {
            if (data != null) {
                List<GuidData> xs = data.getParcelableArrayListExtra("device");
                if (xs != null && xs.size() > 0) {
                    //开始自动选型
                    ProjectManager.getInstance().setProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_QXSYKT, xs.get(0).getGuidId());
                    getDefaultQxsyktDevice();
                }
            }
        }
    }

    /***
     * 对室内机自动选型
     */
    private void getDefaultSNJDevice() {
        if (StringUtils.isEmpty(ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SNJ))) {
            IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            return;
        }

        mProgressDlg = createProgressBarDialog(ProjectStep4Activity.this, "自动选型中...");
        mProgressDlg.show();
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("xsid", ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_SNJ));

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_ALL_ROOMS_AUTO_SNJ, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetIndoorEquipDataResp>() {
            @Override
            public void onSuccess(GetIndoorEquipDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                if (obj.getAutoAllRoomSnjEquipResult() != null && obj.getAutoAllRoomSnjEquipResult().size() > 0) {
                    String str = "以下房间室内机选型失败：\n";
                    for (RoomData item : obj.getAutoAllRoomSnjEquipResult()) {
                        str += item.getName();
                        str += " ";
                    }

                    IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", str, "确认", null);
                }
                else {
                    showMessage("室内机选型成功！");
                }
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            }
        });

    }

    /***
     * 对室内机自动选型
     */
    private void getDefaultQxsyktDevice() {
        if (StringUtils.isEmpty(ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_QXSYKT))) {
            IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            return;
        }

        mProgressDlg = createProgressBarDialog(ProjectStep4Activity.this, "自动选型中...");
        mProgressDlg.show();
        Map<String, Object> param = new HashMap<>();
        param.put("pid", ProjectManager.getInstance().getProjectData().getGuidId());
        param.put("xsid", ProjectManager.getInstance().getProjectDefaultSeries(ProjectInfoData.MACHINE_TAG_FOR_QXSYKT));

        BasicHttpClient.httpGetAsync(HttpConstant.HTTP_GET_PROJECT_ALL_ROOMS_AUTO_QXSYKT, AccountManager.getInstance().getToken(), param, new HttpCallbackHandle<GetIndoorEquipDataResp>() {
            @Override
            public void onSuccess(GetIndoorEquipDataResp obj) {
                // 成功
                mProgressDlg.dismiss();
                if (obj.getAutoAllRoomQxSyktEquipResult() != null && obj.getAutoAllRoomQxSyktEquipResult().size() > 0) {
                    String str = "以下房间轻型商用空调选型失败：\n";
                    for (RoomData item : obj.getAutoAllRoomQxSyktEquipResult()) {
                        str += item.getName();
                        str += " ";
                    }

                    IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", str, "确认", null);
                }
                else {
                    showMessage("轻型商用空调选型成功！");
                }
            }

            @Override
            public void onFailure(String response) {
                mProgressDlg.dismiss();
                IOSAlertView.showAlertView(ProjectStep4Activity.this, "提示", "超出该系列能力范围，请选择其他合适型式。", "确认", null);
            }
        });

    }

}
